# coding: utf-8

from operator import index
from typing import List
from PyQt5 import QtCore
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QStackedWidget, QCompleter
from PyQt5.QtCore import Qt, QThreadPool, QThread
from PyQt5.QtGui import QIcon, QPixmap

from qfluentwidgets import (
    CardWidget,
    PushButton,
    LineEdit,
    BodyLabel,
    SmoothScrollArea,
    FlowLayout,
)

from app.components.pageFlipWidget import PageTurningWidget
from app.common.load_resources import LoadResourceThread
from app.common.load_resources import ThreadStartsResourceLoading, ThreadLoadPool
from app.components.resourceCard import ResourceCard

MAP_KEYWORDS = []

# 添加资源包关键字为搜索框提供提示
def setKeyWords(name):
    MAP_KEYWORDS.append(name)


""" 资源包资源界面搜索框 """


class SearchCard(CardWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        # 初始化组件
        self.titleLabel = BodyLabel(self)
        self.searchLineEdit = LineEdit(self)
        self.searchButton = PushButton(self)

        self.__initWidget()

    def __initWidget(self):
        self.setEnabled(False)
        # 设置组件
        self.titleLabel.setText(self.tr("SEARCH CARD(temporarily unavailable)"))

        self.searchLineEdit.setPlaceholderText(
            self.tr("what pack resources do you want to search?")
        )

        self.searchButton.setText(self.tr("Search"))
        self.searchButton.setMaximumWidth(200)

        self.__initLayout()

    def __initLayout(self):
        # 初始化布局
        self.layouts = QVBoxLayout(self)
        self.hBoxLayout = QHBoxLayout()
        self.setLayout(self.layouts)

        self.layouts.addWidget(
            self.titleLabel, 0, Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft
        )
        self.layouts.addLayout(self.hBoxLayout)

        self.hBoxLayout.addWidget(self.searchLineEdit)
        self.hBoxLayout.addWidget(self.searchButton)


""" 资源包资源界面资源显示区 """


class PackScrollArea(SmoothScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.widgets = QWidget(self)

        self.__initWidget()

    def __initWidget(self):
        self.setObjectName("PackScrollArea")
        self.setWidgetResizable(True)
        self.setWidget(self.widgets)
        self.setStyleSheet(
            "#PackScrollArea{" "background:transparent;" "border:none;" "}"
        )

        self.widgets.setObjectName("PackScrollAreaWidget")
        self.widgets.setStyleSheet(
            "#PackScrollAreaWidget{" "background:transparent;" "}"
        )

        self.__initLayout()

    def __initLayout(self):
        self.layouts = FlowLayout(self.widgets)
        self.widgets.setLayout(self.layouts)

    def loadWidget(self, widget: QWidget):
        self.layouts.addWidget(widget)


""" 资源包总界面 """


class PackInterface(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.pages = 0

        self.searchCard = SearchCard(self)
        self.flipStackedWidget = QStackedWidget(self)
        self.scrollAreaList: List[PackScrollArea] = []

        self.__initWidget()
        self.__initPage()

    def __initWidget(self):
        self.setObjectName("packInterface")

        self.flipStackedWidget.setObjectName("flipStackedWidget")
        self.flipStackedWidget.setStyleSheet(
            "#flipStackedWidget{" "background:transparent;" "border-radius: 8px;" "}"
        )

        self.__initLayout()

    def __initLayout(self):
        self.layouts = QVBoxLayout(self)
        self.layouts.addWidget(self.searchCard, 0, Qt.AlignmentFlag.AlignTop)
        self.layouts.addWidget(self.flipStackedWidget)

    def __initPage(self):
        self.pageLoad = LoadResourceThread(14, "", "getPage", page=1)
        self.pageLoad.pageNumber.connect(lambda num: self._createFlip(num))

        self.pageLoad.start()

    def __initResources(self):
        self.poolList = []
        for i in range(1, self.pages + 1):
            resourceLoad = None
            mapScrollArea = None
            mapScrollArea = PackScrollArea(self.flipStackedWidget)
            self.flipStackedWidget.addWidget(mapScrollArea)
            self.scrollAreaList.append(mapScrollArea)

            resourceLoad = LoadResourceThread(14, "", "getResource", i)
            resourceLoad.pageCardInformation.connect(
                lambda x: self._loadResourceCard(x)
            )

            self.poolList.append(resourceLoad)
        # for thread in self.poolList:
        #     thread.start()
        threadLoad = ThreadStartsResourceLoading(self.poolList)
        ThreadLoadPool.start(threadLoad)

    def _loadResourceCard(self, resources):
        page = resources["currentPage"]

        try:
            authorDict = {
                "Id": resources["authorId"],
                "Name": resources["authorNickname"],
                "Avatar": resources["authorAvatar"],
            }
        except Exception as e:
            authorDict = {
                "Id": resources["authorId"],
                "Name": "请求作者名时出错",
                "Avatar": "null",
            }
            print(f"请求作者信息时出错 ->\n{e}")

        self.scrollAreaList[page - 1].loadWidget(
            ResourceCard(
                resources["coverImage"],
                resources["resourceTitle"],
                authorDict,
                resources["resourceId"],
                resources["updatedAt"],
                resources["resourceSummary"],
                self.scrollAreaList[page - 1].widgets,
            )
        )
        # 保持关键字更新
        setKeyWords(resources["resourceTitle"])
        self.completer = QCompleter(MAP_KEYWORDS, self.searchCard.searchLineEdit)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setMaxVisibleItems(15)
        self.searchCard.searchLineEdit.setCompleter(self.completer)

    def _createFlip(self, pages):
        self.pages = pages
        self.pageFlip = PageTurningWidget(self, pages)
        self.pageFlip.pageChangeSignal.connect(
            lambda x: self.flipStackedWidget.setCurrentIndex(x - 1)
        )
        self.layouts.addWidget(
            self.pageFlip,
            0,
            Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignHCenter,
        )

        self.__initResources()
